<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="modelValue"
    @close="closeForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ file.opera === "add" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar class="ba-table-form-scrollbar" v-loading="state.loading">
      <div
        class="ba-operate-form"
        :style="'width: calc(100% - ' + state.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="onAddSubmit(formRef)"
          :model="state.form"
          label-position="right"
          label-width="160px"
          :rules="rules"
        >
          <el-form-item label="文件名称" prop="fileName">
            <el-input
              v-model="state.form!.fileName"
              placeholder="请输入文件名称"
            />
          </el-form-item>
          <el-form-item label="材料文件" prop="fileUrl">
            <el-upload
              ref="uploadPdfRef"
              v-model:file-list="pdfFileList"
              :limit="1"
              accept=".doc,.docx,.xlsx,.pdf,.jpg,.png,.jpeg"
              class="upload-demo"
              :action="state.fileAction1"
              :auto-upload="false"
              :on-change="changUploadPdf"
              :on-remove="handleRemovePdf"
            >
              <el-button type="primary">上传本地文件</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持doc、docx、xlsx、pdf 、jpg等常见文件格式
                </div>
              </template>
            </el-upload>
            <el-link
              @click="equipSpecifications(state.form!.fileUrl)"
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              >{{ state.form!.fileUrl }}</el-link
            >
          </el-form-item>
          <el-form-item label="视频文件" prop="videoUrl">
            <el-upload
              ref="uploadVideoRef"
              v-model:file-list="pdfFileList"
              :limit="1"
              accept=".mp4"
              class="upload-demo"
              :action="state.fileAction1"
              :auto-upload="false"
              :on-change="changUploadVideo"
              :on-remove="handleRemoveVideo"
            >
              <el-button type="primary">上传本地视频</el-button>
              <template #tip>
                <div class="el-upload__tip">支持mp4等常见视频格式</div>
              </template>
            </el-upload>
            <el-link
              @click="equipSpecifications(state.form!.videoUrl)"
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              >{{ state.form!.videoUrl }}</el-link
            >
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div :style="'width: calc(100% - ' + state.labelWidth / 1.8 + 'px)'">
        <el-button @click="closeForm">取消</el-button>
        <el-button
          v-blur
          :loading="state.submitLoading"
          @click="onAddSubmit(formRef)"
          type="primary"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {
  reactive,
  ref,
  inject,
  onMounted,
  computed,
  nextTick,
  onBeforeUnmount,
} from "vue";
// import type baTableClass from "@/utils/baTable";
import type {
  ElForm,
  FormRules,
  UploadFile,
  UploadFiles,
  FormInstance,
} from "element-plus";
import { _download, _upload } from "@/utils/axios";
import { useConfig } from "@/store/config"; //后台布局相关仓库
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useRoute, useRouter } from "vue-router";
import type { UploadProps, UploadUserFile, UploadInstance } from "element-plus";
import { ElNotification } from "element-plus"; //处理导航信息
import { useLedgerFile } from "@/store/backend/BusinessM/file";

type Option = {
  id: number;
  label: string;
  children: Option[];
};

//接受来自父组件的注入
// const baTable = inject("baTable") as baTableClass;
const formRef = ref<InstanceType<typeof ElForm>>();
const config = useConfig();
const route = useRoute();
const file = useLedgerFile();
const { proxy } = useCurrentInstance();
const uploadPdfRef = ref<UploadInstance>();

const fileList = ref<UploadUserFile[]>([
  //   {
  //     name: "",
  //     url: "",
  //   },
]);

interface Props {
  modelValue: boolean;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
});

const state: {
  form: anyObj;
  fileAction1: string;
  fileAction2: string;
  fileAction3: string;
  host: string;
  labelWidth: number;
  submitLoading: boolean;
  loading: boolean;
} = reactive({
  labelWidth: 160,
  submitLoading: false,
  form: {
    id: 0,
    orderId: 0,
    fileName: "",
    fileUrl: "",
    isNecessary: "",
    companyId: 0,
    companyName: "",
    videoUrl: "",
  },
  fileAction1: "", //上传pdf文件的服务器地址
  fileAction2: "",
  fileAction3: "",
  host: "",
  loading: false,
});

const emits = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
}>();
const closeForm = () => {
  emits("update:modelValue", false);
  state.form = {
    id: 0,
    orderId: 0,
    fileName: "",
    fileUrl: "",
    isNecessary: "",
    companyId: 0,
    companyName: "",
  };
};

//视频文件
const videoFileList = ref<UploadUserFile[]>([]);
const videoRealFileList = ref<UploadUserFile[]>([]);

//说明书pdf
const pdfFileList = ref<UploadUserFile[]>([]);
const pdfRealUploadFile = ref<UploadUserFile[]>([]);

const headerConfig = {
  Authorization: JSON.parse(localStorage.getItem("adminInfo") as any)?.token,
};

//移除说明书pdf
const handleRemovePdf: UploadProps["onRemove"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles, pdfFileList);
  const { uid } = uploadFile;
  const selectFileList = pdfFileList.value.filter((item) => {
    return item.uid != uid;
  });
  pdfFileList.value = selectFileList;
};
//设备说明书pdf文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changUploadPdf: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  state.loading = true;
  console.log("文件限制", uploadFile, uploadFiles, pdfFileList);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png",
    });
    const selectFileList = pdfFileList.value.filter((item) => {
      return item.uid != uid;
    });
    pdfFileList.value = selectFileList;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过5Mb",
    });
    const selectFileList = pdfFileList.value.filter((item) => {
      return item.uid != uid;
    });
    pdfFileList.value = selectFileList;
    return;
  }
  // 将上传PDF说明书文件信息存入列表
  pdfFileList.value.push(uploadFile);
  pdfRealUploadFile.value = [];
  let formData = new FormData();
  formData.append("file", uploadFiles[0].raw as any); //添加文件对象
  formData.append("name", "pdf"); //添加文件对象
  _upload("/common/upload", formData, "").then((res: any) => {
    // baTable.form.items!.information = res.data.url;
    // state.form!.fileUrl =
    //   state.host === "" ? res.data.url : state.host + res.data.fileName;
    state.form!.fileUrl =
      state.host === "" ? res.data.url : state.host + res.data.fileName;
    // state.form!.fileUrl = res.data.url;
    state.loading = false;
  });
};
//允许自行实现上传文件的请求 再用户触发了realSubmit后触发
// const handleUplodFilePdf = (options: UploadRequestOptions) => {
//   console.log("允许自行实现上传文件的请求", options);
//   pdfRealUploadFile.value.push(options.file);
//   let formData = new FormData();
//   formData.append("file", options.file); //添加文件对象
//   formData.append("name", "pdf"); //添加文件对象
//   _upload("/common/upload", formData, "").then((res: any) => {
//     state.form.information = res.data.url;
//     //再上传cep图片
//     uploaCepfRef.value!.submit();
//   });
// };

//移除视频文件
const handleRemoveVideo: UploadProps["onRemove"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles, videoFileList);
  const { uid } = uploadFile;
  const selectFileList = videoFileList.value.filter((item) => {
    return item.uid != uid;
  });
  videoFileList.value = selectFileList;
};
//视频文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changUploadVideo: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("文件限制", uploadFile, uploadFiles, videoFileList);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.mp4|.mp5$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png",
    });
    const selectFileList = videoFileList.value.filter((item) => {
      return item.uid != uid;
    });
    videoFileList.value = selectFileList;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过5Mb",
    });
    const selectFileList = videoFileList.value.filter((item) => {
      return item.uid != uid;
    });
    videoFileList.value = selectFileList;
    return;
  }
  // 将上传PDF说明书文件信息存入列表
  videoFileList.value.push(uploadFile);
  videoRealFileList.value = [];
  let formData = new FormData();
  formData.append("file", uploadFiles[0].raw as any); //添加文件对象
  formData.append("name", "pdf"); //添加文件对象
  _upload("/common/upload", formData, "").then((res: any) => {
    // baTable.form.items!.information = res.data.url;
    // baTable.form.items!.fileUrl =
    //   state.host === "" ? res.data.url : state.host + res.data.fileName;
    state.form!.videoUrl =
      state.host === "" ? res.data.url : state.host + res.data.fileName;
    // state.form!.fileUrl = res.data.url;
  });
};

//规则
const rules = reactive<FormRules>({
  fileName: [{ required: true, message: "文件名称不能为空", trigger: "blur" }],
  fileUrl: [{ required: true, message: "材料文件不能为空", trigger: "blur" }],
});

//提交表单
// const realSubmit = (formEl: FormInstance | undefined) => {
//   baTable.form.items.orderId = route.query.orderId; //文件名对应的id
//   baTable.form.items.companyId = route.query.companyId; //企业id
//   nextTick(() => {
//     baTable.onSubmit(formRef.value);
//   });
// };
//提交文件表单
const onAddSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      if (file.opera === "edit") {
        file.editFile(state.form).then((res) => {
          closeForm();
          proxy.eventBus.emit("refreshFile"); //刷新文件列表
        });
      } else {
        file.addFile(state.form).then((res) => {
          closeForm();
          proxy.eventBus.emit("refreshFile"); //刷新文件列表
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

//编辑文件表单
proxy.eventBus.on("editFile", (data: any) => {
  console.log("editFile", data);
  state.form = data;
});

//接收台账目录数据 并打开文件表单
proxy.eventBus.on("addFile", (data: any) => {
  console.log("addFile", data);
  state.form.orderId = data.id; //文件名对应的id
  state.form.companyId = route.query.companyId; //企业id
});

//针对侧边栏菜单高度让滚动条自适应
const overviewMenusScrollbarHeight = computed(() => {
  // 加上了50px的头部距离
  let menuTopBarHeight = 50;
  if (config.layout.layoutMode == "Default") {
    //32为aside上下margin
    return "calc(100vh - " + (172 + menuTopBarHeight) + "px)";
  } else {
    return "calc(100vh - " + (140 + menuTopBarHeight) + "px)";
  }
});

const equipSpecifications = (url: any) => {
  window.open(url);
};

//获取域名进行拼接
const getBaseUrl = () => {
  let url = window.location;
  console.log("获取域名进行拼接", url.origin, url.origin.includes("s"));
  if (url.origin.includes("180")) {
    //https
    state.host = url.origin;
  } else {
    state.host = "";
  }
};
getBaseUrl();

onMounted(() => {
  console.log("route", route.query);
});
onBeforeUnmount(() => {
  proxy.eventBus.off("editFile");
  proxy.eventBus.off("addFile");
});
// defineExpose({
//   getCheckeds,
// });
// watch(filterText, (val) => {
//   treeRef2.value!.filter(val);
// });
// watch(filterTextIOT, (val) => {
//   treeRef3.value!.filter(val);
// });
</script>
<style lang="scss" scoped>
.filter-tree {
  height: 200px;
}
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
.vertical-menus-scrollbar {
  height: v-bind(overviewMenusScrollbarHeight);
}
</style>
